package com.shuwen.gcdj.service.statistic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuwen.gcdj.bean.conditionMonitoring.request.*;
import com.shuwen.gcdj.bean.conditionMonitoring.response.*;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.FieldUtil;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.entity.statistics.StatisticsHealth;
import com.shuwen.gcdj.entity.statistics.StatisticsMechanismvibration;
import com.shuwen.gcdj.entity.statistics.StatisticsShocksensorfrequency;
import com.shuwen.gcdj.entity.statistics.StatisticsTrendstability;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsHealthMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsMechanismvibrationMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsShocksensorfrequencyMapper;
import com.shuwen.gcdj.mapper.mysql.Statistic.StatisticsTrendstabilityMapper;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.service.sysDictionary.SysDictionaryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Yangx
 */
@Service
@AllArgsConstructor
@Slf4j
public class FaultMonitoringService {
    private final SysDictionaryMapper sysDictionaryMapper;
    private final StatisticsHealthMapper statisticsHealthMapper;
    private final StatisticsTrendstabilityMapper statisticsTrendstabilityMapper;
    private final StatisticsMechanismvibrationMapper statisticsMechanismvibrationMapper;
    private final StatisticsShocksensorfrequencyMapper statisticsShocksensorfrequencyMapper;
    private final com.shuwen.gcdj.mapper.tdengine.Statistic.StatisticStressMetersMapper statisticStressMetersMapper;
    private final SysDictionaryService sysDictionaryService;

    public CommonResult<StrainSensorTendencyNowResp> getStrainSensorTendencyByNow(StrainSensorTendencyByNowReq req) {
        StrainSensorTendencyNowResp strainSensorTendencyNowResp = new StrainSensorTendencyNowResp();
        StatisticsTrendstabilityQueryReq statisticsTrendstabilityQueryReq = new StatisticsTrendstabilityQueryReq();
        statisticsTrendstabilityQueryReq.setEquipmentCode(req.getEquipmentCode());
        statisticsTrendstabilityQueryReq.setMonitorLocation(Constants.GIRDER_TRANSFORMATION_VALUE);
        //获取当日最新数据
        LocalDate localDate = LocalDate.now();
        statisticsTrendstabilityQueryReq.setYear(localDate.getYear());
        statisticsTrendstabilityQueryReq.setMonth(localDate.getMonthValue());
        statisticsTrendstabilityQueryReq.setDay(localDate.getDayOfMonth());
        StatisticsTrendstabilityResp statisticsTrendstabilityResp = statisticsTrendstabilityMapper.getSingle(statisticsTrendstabilityQueryReq);
        if (statisticsTrendstabilityResp != null) {
            float value = statisticsTrendstabilityResp.getStatusValue();
            strainSensorTendencyNowResp.setTendencyValue(String.format("%.2f", value));
        }
        return CommonResult.success(strainSensorTendencyNowResp);
    }

    public CommonResult<List<SensorPointPositionResp>> getStrainSensor(StrainSensorPointQueryReq req) {
        List<SensorPointPositionResp> sensorPointPositionRespList;
        //根据对应设备类型和编号，分别查询应变传感器点位
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.STRAIN_SENSOR_POINT);
        sysDictionaryReq.setOperateObject(req.getEquipmentCode());
        //根据设备编号和设备类型查点位字典配置
        sensorPointPositionRespList = sysDictionaryMapper.getList(sysDictionaryReq).stream().map(
                temp -> {
                    SensorPointPositionResp obj = new SensorPointPositionResp();
                    obj.setName(temp.getName());
                    obj.setCode(temp.getCode());
                    obj.setOrder(temp.getValue());
                    return obj;
                }
        ).collect(Collectors.toList()).stream().sorted(Comparator.comparing(SensorPointPositionResp::getOrder)).collect(Collectors.toList());
        //获取每个配置对应的点位编号信息
        List<String> parentCodeList = sensorPointPositionRespList.stream().map(SensorPointPositionResp::getCode).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(parentCodeList)) {
            List<SysDictionary> pointDetailList = sysDictionaryMapper.selectList(new LambdaQueryWrapper<SysDictionary>()
                    .in(SysDictionary::getParentCode, parentCodeList)
                    .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL)
            );
            sensorPointPositionRespList.forEach(t -> {
                List<SysDictionary> pointList = pointDetailList.stream().filter(point -> point.getParentCode().equals(t.getCode()) && point.getOperateObject().equals(req.getEquipmentCode())).collect(Collectors.toList());
                t.setPointCodes(pointList.stream().map(SysDictionary::getCode).collect(Collectors.toList()));
            });
        }

        return CommonResult.success(sensorPointPositionRespList);
    }

    /**
     * 获取倾角传感器
     *
     * @param req
     * @return
     */
    public CommonResult<List<SensorPointPositionResp>> getTiltSensor(TiltSensorPointReq req) {
        List<SensorPointPositionResp> sensorPointPositionRespList;
        //根据对应设备类型和编号，分别查询应变传感器点位
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.TILT_SENSOR_POINT);
        sysDictionaryReq.setOperateObject(req.getEquipmentCode());
        //根据设备编号和设备类型查点位字典配置
        sensorPointPositionRespList = sysDictionaryMapper.getList(sysDictionaryReq).stream().map(
                temp -> {
                    SensorPointPositionResp obj = new SensorPointPositionResp();
                    obj.setName(temp.getName());
                    obj.setCode(temp.getCode());
                    obj.setOrder(temp.getValue());
                    return obj;
                }
        ).collect(Collectors.toList()).stream().sorted(Comparator.comparing(SensorPointPositionResp::getOrder)).collect(Collectors.toList());
        //获取每个配置对应的点位编号信息
        List<String> parentCodeList = sensorPointPositionRespList.stream().map(SensorPointPositionResp::getCode).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(parentCodeList)) {
            List<SysDictionary> pointDetailList = sysDictionaryMapper.selectList(new LambdaQueryWrapper<SysDictionary>()
                    .in(SysDictionary::getParentCode, parentCodeList)
                    .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL)
            );
            sensorPointPositionRespList.forEach(t -> {
                List<SysDictionary> pointList = pointDetailList.stream().filter(point -> point.getParentCode().equals(t.getCode()) && point.getOperateObject().equals(req.getEquipmentCode())).collect(Collectors.toList());
                t.setPointCodes(pointList.stream().map(SysDictionary::getCode).collect(Collectors.toList()));
            });
        }

        return CommonResult.success(sensorPointPositionRespList);
    }

    public CommonResult<List<StrainSensorResp>> getSensorPointPosition(VibratingSensorPointReq req) {
        if(StringUtils.isEmpty( req.getEquipmentCode())){
            return CommonResult.failed("请选择设备");
        }
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.VIBRATING_SENSOR_POINT);
        sysDictionaryReq.setOperateObject(req.getEquipmentCode());
        List<StrainSensorResp> LiftList = sysDictionaryMapper.getList(sysDictionaryReq).stream().map(
                temp -> {
                    StrainSensorResp strainSensorResp = new StrainSensorResp();
                    strainSensorResp.setName(temp.getName());
                    strainSensorResp.setOrder(temp.getValue());
                    strainSensorResp.setCode(temp.getCode());
                    return strainSensorResp;
                }
        ).collect(Collectors.toList()).stream().sorted(Comparator.comparing(StrainSensorResp::getOrder)).collect(Collectors.toList());
        //获取每个配置对应的点位编号信息
        List<String> parentCodeList = LiftList.stream().map(StrainSensorResp::getCode).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(parentCodeList)) {
            List<SysDictionary> pointDetailList = sysDictionaryMapper.selectList(new LambdaQueryWrapper<SysDictionary>()
                    .in(SysDictionary::getParentCode, parentCodeList)
                    .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL)
            );
            LiftList.forEach(t -> {
                //获取起升机构下的点位信息
                List<SysDictionary> liftPointList = pointDetailList.stream().filter(point -> point.getParentCode().equals(t.getCode()) && point.getOperateObject().equals(req.getEquipmentCode())).collect(Collectors.toList());
                List<String> liftObjectList = liftPointList.stream().map(SysDictionary::getName).distinct().collect(Collectors.toList());
                List<VibratingObjectItemResp> sensorPointPositionRespList = liftObjectList.stream().map(
                        item -> {
                            VibratingObjectItemResp sensorPointPositionResp = new VibratingObjectItemResp();
                            sensorPointPositionResp.setName(item);
                            sensorPointPositionResp.setPointCodes(liftPointList.stream().filter(point -> point.getName().equals(item)).map(SysDictionary::getCode).collect(Collectors.toList()));
                            return sensorPointPositionResp;
                        }).collect(Collectors.toList());
                t.setPointCodes(sensorPointPositionRespList);
            });
        }

        return CommonResult.success(LiftList);
    }

    public CommonResult<List<StatisticsHealthResp>> getShockSensor(ShockSensorQueryReq req) {
        List<StatisticsHealthResp> statisticsHealthRespList = new ArrayList<>();
        List<String> dateValue = new ArrayList<>();
        List<Double> healthValue = new ArrayList<>();
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setCodes(req.getLocations());
        dictionaryReq.setParentCode(req.getParentCode());
        dictionaryReq.setOperateObject(req.getEquipmentCode());
        //根据点位名称与父级编号，查询传感器点位编号
        List<Integer> locations = sysDictionaryMapper.getList(dictionaryReq).stream().map(SysDictionaryResp::getValue).collect(Collectors.toList());
        //查询载荷图谱数据
        //获取当日最新数据
        LocalDate localDate = LocalDate.now();
        List<StatisticsShocksensorfrequency> loads = statisticsShocksensorfrequencyMapper.selectList(new QueryWrapper<StatisticsShocksensorfrequency>()
                .lambda().eq(StatisticsShocksensorfrequency::getEquipmentCode, req.getEquipmentCode())
                .eq(StatisticsShocksensorfrequency::getMonitoringObject, Integer.valueOf(req.getMonitoringObject()))
                .eq(StatisticsShocksensorfrequency::getYear, localDate.getYear())
                .eq(StatisticsShocksensorfrequency::getMonth, localDate.getMonthValue())
                .eq(StatisticsShocksensorfrequency::getDay, localDate.getDayOfMonth())
                .eq(StatisticsShocksensorfrequency::getIsDelete, Constants.IS_DELETE_NORMAL)
                .in(StatisticsShocksensorfrequency::getLocation, locations)
        ).stream().sorted(Comparator.comparing(StatisticsShocksensorfrequency::getTime).reversed()).collect(Collectors.toList());
        //判断如果载荷图谱为空，传给前端默认数据
        if (loads == null || loads.isEmpty()) {
            dateValue.add(Constants.ZERO.toString());
            healthValue.add((double) Constants.ZERO);
            StatisticsHealthResp statisticsHealthResp = new StatisticsHealthResp();
            statisticsHealthResp.setName(Constants.HORIZONTAL_DIRECTION);
            statisticsHealthResp.setDateValue(dateValue);
            statisticsHealthResp.setHealthValue(healthValue);
            statisticsHealthRespList.add(statisticsHealthResp);
            StatisticsHealthResp statisticsHealthResp1 = new StatisticsHealthResp();
            statisticsHealthResp1.setDateValue(dateValue);
            statisticsHealthResp1.setHealthValue(healthValue);
            statisticsHealthResp1.setName(Constants.VERTICAL_DIRECTION);
            statisticsHealthRespList.add(statisticsHealthResp1);
            return CommonResult.success(statisticsHealthRespList);
        }
        //查询载荷信息，并对载荷信息进行处理和排序
        //获取约定的竖直和水平值
        List<Integer> directionList = new ArrayList<>();
        directionList.add(Constants.VERTICAL_DIRECTION_VALUE);
        directionList.add(Constants.HORIZONTAL_DIRECTION_VALUE);
        directionList.forEach(temp -> {
            StatisticsShocksensorfrequency load = loads.stream().filter(e -> e.getDirection().equals(temp)).findFirst().orElse(null);
            List<String> list = load != null ? WorkingConditionsService.solveUrl(load.getFrequencyDomain()) : new ArrayList<>();
            List<LoadByOrderResp> loadByOrderRespList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                List<LoadByOrderResp> finalLoadByOrderRespList = new ArrayList<>();
                list.forEach(item ->
                {
                    String[] ary = item.split(",");
                    LoadByOrderResp loadByOrderResp = new LoadByOrderResp();
                    loadByOrderResp.setIndex(Double.valueOf(ary[0]));
                    loadByOrderResp.setValue(Double.valueOf(ary[1]));
                    finalLoadByOrderRespList.add(loadByOrderResp);
                });
                loadByOrderRespList = finalLoadByOrderRespList.stream().sorted(Comparator.comparing(LoadByOrderResp::getIndex)).collect(Collectors.toList());
            } else {
                LoadByOrderResp loadByOrderResp = new LoadByOrderResp();
                loadByOrderResp.setIndex(Double.valueOf(Constants.ZERO));
                loadByOrderResp.setValue((double) Constants.ZERO);
                loadByOrderRespList.add(loadByOrderResp);
            }
            //1、竖直方向；2、水平方向；
            StatisticsHealthResp healthResp = new StatisticsHealthResp();
            //1、竖直方向；2、水平方向；
            healthResp.setName(temp.equals(Constants.ONE) ?Constants.VERTICAL_DIRECTION : Constants.HORIZONTAL_DIRECTION);
            healthResp.setDateValue(loadByOrderRespList.stream().map(loadByOrderResp -> loadByOrderResp.getIndex().toString()).collect(Collectors.toList()));
            healthResp.setHealthValue(loadByOrderRespList.stream().map(LoadByOrderResp::getValue).collect(Collectors.toList()));
            healthResp.setDirection(temp);
            statisticsHealthRespList.add(healthResp);
        });
        return CommonResult.success(statisticsHealthRespList);
    }

    public List<StatusSensorDateNowResp> getStrainSensorByDateNow(StrainSensorDateNowQueryReq req) {
        List<StatusSensorDateNowResp> statusSensorDateNowRespList = new ArrayList<>();
        //获取点位信息
        SysDictionaryReq sysDictionReq = new SysDictionaryReq();
        sysDictionReq.setCodes(req.getCode());
        sysDictionReq.setParentCode(req.getParentCode());
        sysDictionReq.setOperateObject(req.getEquipmentCode());
        List<SysDictionaryResp> strainRealTimeSensor = sysDictionaryMapper.getList(sysDictionReq);
        //获取区间配置
        sysDictionReq = new SysDictionaryReq();
        sysDictionReq.setParentCode(Constants.SENSOR_STATISTICS);
        List<SysDictionaryResp> dictionaryModels = sysDictionaryMapper.getList(sysDictionReq);
        //获取子表配置
        sysDictionReq = new SysDictionaryReq();
        sysDictionReq.setParentCode(Constants.EQUIPMENT_CODE_TDSTABLE);
        List<SysDictionaryResp> dictionary = sysDictionaryMapper.getList(sysDictionReq);

        switch (req.getSensorType()) {
            case 1: //倾角
                StressMetersReq tiltMetersReq = new StressMetersReq();
                //获取配置的查询区间
                SysDictionaryResp tiltSet = dictionaryModels.stream().filter(t -> Objects.equals(t.getValue(), Constants.YELLOW_INCLINATION)).findFirst().orElse(null);
                assert tiltSet != null;
                int tiltSecond = Integer.parseInt(StringUtils.isEmpty(tiltSet.getCode()) ? "1" : tiltSet.getCode());
                int tiltLimit = Integer.parseInt(tiltSet.getName().isEmpty() ? "100" : tiltSet.getName());
                req.setDate(LocalDateTime.now());
                String tiltStartDate = req.getDate().plusMinutes(-tiltSecond).format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                String tiltEndDate = req.getDate().format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                tiltMetersReq.setStartTime(tiltStartDate);
                tiltMetersReq.setEndDateTime(tiltEndDate);
                tiltMetersReq.setEquipmentCode(req.getEquipmentCode());
                tiltMetersReq.setLimit(tiltLimit);
                for (SysDictionaryResp item : strainRealTimeSensor) {
                    SysDictionaryResp sysDictionaryResp = dictionary.stream()
                            .filter(t -> t.getOperateObject().equals(req.getEquipmentCode())
                                    && t.getCode().contains(Constants.GANTRY_CRANE_TILT))
                            .findFirst()
                            .orElse(null);
                    if (sysDictionaryResp == null) {
                        break;
                    }
                    tiltMetersReq.setSensorCode(item.getCode());
                    tiltMetersReq.setTableName(sysDictionaryResp.getCode());
                    List<TDSensorCodeDataAllResp> stressMetersResps = statisticStressMetersMapper.getTiltMetersListA(tiltMetersReq)
                            .stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
                    StatusSensorDateNowResp statusSensorDateNowResp = new StatusSensorDateNowResp();
                    statusSensorDateNowResp.setLocation(item.getRemark());
                    statusSensorDateNowResp.setDateTimeName(stressMetersResps.stream().map(t -> t.getTs().toLocalDateTime().format(DateTimeFormatter.ofPattern(Constants.TD_TIME_FORMAT))).collect(Collectors.toList()));
                    statusSensorDateNowResp.setSpeed(FieldUtil.usersBlankNum(item.getCode(),TDSensorCodeDataAllResp.class,stressMetersResps));
                    statusSensorDateNowRespList.add(statusSensorDateNowResp);
                }
                break;
            case 2: //振动
                StressMetersReq vibratingMetersReq = new StressMetersReq();
                //获取配置的查询区间
                SysDictionaryResp vibratingSet = dictionaryModels.stream().filter(t -> Objects.equals(t.getValue(), Constants.BLUE_VIBRATION)).findFirst().orElse(null);
                assert vibratingSet != null;
                int vibratingSecond = Integer.parseInt(StringUtils.isEmpty(vibratingSet.getCode()) ? "1" : vibratingSet.getCode());
                int vibratingLimit = Integer.parseInt(vibratingSet.getName().isEmpty() ? "100" : vibratingSet.getName());
                req.setDate(LocalDateTime.now());
                String vibratingStartDate = req.getDate().plusSeconds(-vibratingSecond).format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                String vibratingEndDate = req.getDate().format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                vibratingMetersReq.setStartTime(vibratingStartDate);
                vibratingMetersReq.setEndDateTime(vibratingEndDate);
                vibratingMetersReq.setEquipmentCode(req.getEquipmentCode());
                vibratingMetersReq.setLimit(vibratingLimit);
                sysDictionReq = new SysDictionaryReq();
                sysDictionReq.setParentCode(Constants.SENSOR_TABLES);
                List<SysDictionaryResp> tables = sysDictionaryMapper.getList(sysDictionReq);
                for (SysDictionaryResp item : strainRealTimeSensor) {
                    SysDictionaryResp sysDictionaryResp = tables.stream()
                            .filter(t -> t.getOperateObject().equals(req.getEquipmentCode())
                                    && t.getCode() != null
                                    && t.getCode().equals(item.getCode()))
                            .findFirst()
                            .orElse(null);
                    if (sysDictionaryResp == null) {
                        break;
                    }
                    vibratingMetersReq.setTableName(sysDictionaryResp.getName());
                    vibratingMetersReq.setSensorCode(item.getCode());
                    List<TDSensorCodeDataAllResp> stressMetersResps = statisticStressMetersMapper.getVibrationListA(vibratingMetersReq)
                            .stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
                    StatusSensorDateNowResp statusSensorDateNowResp = new StatusSensorDateNowResp();
                    statusSensorDateNowResp.setLocation(item.getRemark());
                    statusSensorDateNowResp.setDateTimeName(stressMetersResps.stream().map(t -> t.getTs().toLocalDateTime().format(DateTimeFormatter.ofPattern(Constants.TD_TIME_FORMAT))).collect(Collectors.toList()));
                    statusSensorDateNowResp.setSpeed(FieldUtil.usersBlankNum(item.getCode(),TDSensorCodeDataAllResp.class,stressMetersResps));
                    statusSensorDateNowRespList.add(statusSensorDateNowResp);
                }
                break;
            case 3: //应变
                StressMetersReq stressMetersReq = new StressMetersReq();
                //获取配置的查询区间
                SysDictionaryResp set = dictionaryModels.stream().filter(t -> Objects.equals(t.getValue(), Constants.RED_STRAIN)).findFirst().orElse(null);
                assert set != null;
                int second = Integer.parseInt(StringUtils.isEmpty(set.getCode()) ? "1" : set.getCode());
                int limit = Integer.parseInt(set.getName().isEmpty() ? "100" : set.getName());
                req.setDate(LocalDateTime.now());
                String startDate = req.getDate().plusMinutes(-second).format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                String endDate = req.getDate().format(DateTimeFormatter.ofPattern(Constants.TD_DATATIME_FORMAT));
                stressMetersReq.setStartTime(startDate);
                stressMetersReq.setEndDateTime(endDate);
                stressMetersReq.setEquipmentCode(req.getEquipmentCode());
                stressMetersReq.setLimit(limit);
                for (SysDictionaryResp item : strainRealTimeSensor) {
                    SysDictionaryResp sysDictionaryResp = dictionary.stream()
                            .filter(t -> t.getOperateObject().equals(req.getEquipmentCode())
                                    && t.getCode().contains(Constants.GANTRY_CRANE_STRAIN))
                            .findFirst()
                            .orElse(null);
                    if (sysDictionaryResp == null) {
                        break;
                    }
                    stressMetersReq.setSensorCode(item.getCode());
                    stressMetersReq.setTableName(sysDictionaryResp.getCode());
                    List<TDSensorCodeDataAllResp> stressMetersResps = statisticStressMetersMapper.getStrainListA(stressMetersReq)
                            .stream().sorted(Comparator.comparing(TDSensorCodeDataAllResp::getTs)).collect(Collectors.toList());
                    StatusSensorDateNowResp statusSensorDateNowResp = new StatusSensorDateNowResp();
                    statusSensorDateNowResp.setLocation(item.getRemark());
                    statusSensorDateNowResp.setDateTimeName(stressMetersResps.stream().map(t -> t.getTs().toLocalDateTime().format(DateTimeFormatter.ofPattern(Constants.TD_TIME_FORMAT))).collect(Collectors.toList()));
                    if (req.getStrainSensorObj() != null && req.getStrainSensorObj() == 2) {
                       List<String> speed = FieldUtil.usersBlankNum(item.getCode(),TDSensorCodeDataAllResp.class,stressMetersResps);
                       List<Double> speedValue =  speed.stream().map(t -> (Double.parseDouble(t) * 0.21)).collect(Collectors.toList());
                        statusSensorDateNowResp.setSpeed(speedValue.stream().map(Object::toString).collect(Collectors.toList()));
                    } else {
                        statusSensorDateNowResp.setSpeed(FieldUtil.usersBlankNum(item.getCode(),TDSensorCodeDataAllResp.class,stressMetersResps));
                    }
                    statusSensorDateNowRespList.add(statusSensorDateNowResp);
                }
                break;
            default:
                break;
        }
        return statusSensorDateNowRespList;
    }

    public CommonResult<StatisticsHealthByIndexResp> getStatisticsHealth(String equipmentCode) {
        //整机健康度
        StatisticsHealthByIndexResp resp = new StatisticsHealthByIndexResp();
        resp.healthVibrationResp = new ArrayList<>();
        HealthQueryReq healthReq = new HealthQueryReq();
        healthReq.setLocation(Constants.ONE);
        healthReq.setEvaluateObject(Constants.COMPLETE_MACHINE);
        healthReq.setEquipmentCode(equipmentCode);
        HealthResp healthResp = statisticsHealthMapper.getSnigle(healthReq);
        if (healthResp != null) {
            resp.setHealthValue(String.valueOf(Math.round(healthResp.getStatusValue())));
        }
        //主梁变形应变趋势值
        StatisticsTrendstabilityQueryReq statisticsTrendstabilityQueryReq = new StatisticsTrendstabilityQueryReq();
        statisticsTrendstabilityQueryReq.setMonitorLocation(Constants.FOUR);
        statisticsTrendstabilityQueryReq.setEvaluateObject(Constants.GIRDER_TRANSFORMATION);
        statisticsTrendstabilityQueryReq.setEquipmentCode(equipmentCode);
        StatisticsTrendstabilityResp statisticsTrendstabilityResp = statisticsTrendstabilityMapper.getSingle(statisticsTrendstabilityQueryReq);
        if (statisticsTrendstabilityResp != null) {
            resp.setStrainValue(String.valueOf(Math.round(statisticsTrendstabilityResp.getStatusValue())));
        }
        //主结构姿态趋势值
        List<StatisticsTrendstability> structureTrendstabilityRespList = statisticsTrendstabilityMapper.selectList(new LambdaQueryWrapper<StatisticsTrendstability>()
                .eq(StatisticsTrendstability::getMonitorLocation, Constants.HOME_MAIN_STRUCTURE_VALUE)
                .eq(StatisticsTrendstability::getEquipmentCode, equipmentCode)
                .eq(StatisticsTrendstability::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(StatisticsTrendstability::getYear, LocalDate.now().getYear())
                .eq(StatisticsTrendstability::getMonth, LocalDate.now().getMonth())
                .eq(StatisticsTrendstability::getDay, LocalDate.now().getDayOfMonth())
        );
        if (!CollectionUtils.isEmpty(structureTrendstabilityRespList)) {
            double trendValue = structureTrendstabilityRespList.stream().mapToDouble(trend -> trend.getStatusValue()).average().getAsDouble();
            resp.setPostureValue(String.valueOf(Math.round(trendValue)));
        }
        //查询对应设备下的起升机构
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.VIBRATING_SENSOR_POINT);
        dictionaryReq.setOperateObject(equipmentCode);
        List<SysDictionaryResp> trendSmoothingType = sysDictionaryMapper.getList(dictionaryReq);
        //查询起升机构振动诊断
        List<StatisticsMechanismvibration> statisticsMechanismvibrationList = statisticsMechanismvibrationMapper.selectList(new LambdaQueryWrapper<StatisticsMechanismvibration>()
                .eq(StatisticsMechanismvibration::getEquipmentCode, equipmentCode)
                .eq(StatisticsMechanismvibration::getIsDelete, Constants.IS_DELETE_NORMAL)
        ).stream().sorted(Comparator.comparing(StatisticsMechanismvibration::getTime).reversed()).collect(Collectors.toList());
        //获取健康度
        List<StatisticsHealth> healthList = statisticsHealthMapper.selectList(new QueryWrapper<StatisticsHealth>()
                .lambda().eq(StatisticsHealth::getEquipmentCode, equipmentCode)
                .eq(StatisticsHealth::getIsDelete, Constants.IS_DELETE_NORMAL)
        ).stream().sorted(Comparator.comparing(StatisticsHealth::getTime).reversed()).collect(Collectors.toList());
        for (SysDictionaryResp item : trendSmoothingType) {
            //起升机构振动诊断结果
            StatisticsMechanismvibration mechanismvibration = statisticsMechanismvibrationList.stream().filter(t -> t.getPosition().equals(item.getValue())).findFirst().orElse(null);
            //起升机构卷筒健康度
            StatisticsHealth health = healthList.stream().filter(heal -> heal.getLocation().equals(Constants.HEALTH_RELL_VALUE) && item.getValue().toString().equals(heal.getRemark())).findFirst().orElse(null);
            HealthVibrationResp healthVibrationResp = new HealthVibrationResp();
            //起升机构名称
            healthVibrationResp.setName(item.getName());
            if (mechanismvibration != null) {
                healthVibrationResp.setShockSensor(mechanismvibration.getInstitutionalVibration());
            }
            if (health != null) {
                healthVibrationResp.setValue(String.valueOf(Math.round(health.getStatusValue())));
            }

            resp.healthVibrationResp.add(healthVibrationResp);
        }
        return CommonResult.success(resp);
    }

    /**
     * 获取倾角传感器历史趋势
     * @param req
     * @return
     */
    public CommonResult<List<TiltTrendstabilityHistoryResp>> getTiltTrendstabilityHistory(TiltTrendstabilityHistoryReq req) {
        List<TiltTrendstabilityHistoryResp> tiltTrendstabilityHistoryRespList = new ArrayList<>();
        //获取当日最新
        LocalDate date = LocalDate.now();
        List<StatisticsTrendstability> statisticsTrendstabilityList = statisticsTrendstabilityMapper.selectList(new LambdaQueryWrapper<StatisticsTrendstability>()
                .eq(StatisticsTrendstability::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(StatisticsTrendstability::getEquipmentCode, req.getEquipmentCode())
                .eq(StatisticsTrendstability::getMonitorLocation, Constants.HOME_MAIN_STRUCTURE_VALUE)
                .eq(StatisticsTrendstability::getYear, date.getYear())
                .eq(StatisticsTrendstability::getMonth, date.getMonthValue())
                .eq(StatisticsTrendstability::getDay, date.getDayOfMonth())
        ).stream().sorted(Comparator.comparing(StatisticsTrendstability::getTime).reversed()).collect(Collectors.toList());
        //获取检测对象
        List<String> evaluateList = statisticsTrendstabilityList.stream().map(StatisticsTrendstability::getEvaluateObject).distinct().collect(Collectors.toList());
        evaluateList.forEach(evaluate -> {
            StatisticsTrendstability trendstability = statisticsTrendstabilityList.stream().filter(trend -> trend.getEvaluateObject().equals(evaluate)).findFirst().orElse(null);
            if (trendstability != null) {
                TiltTrendstabilityHistoryResp tiltTrendstabilityHistoryResp = new TiltTrendstabilityHistoryResp();
                tiltTrendstabilityHistoryResp.setName(trendstability.getEvaluateObject());
                tiltTrendstabilityHistoryResp.setValue(Float.valueOf(String.format("%.2f", trendstability.getStatusValue())));
                tiltTrendstabilityHistoryRespList.add(tiltTrendstabilityHistoryResp);
            }

        });
        return CommonResult.success(tiltTrendstabilityHistoryRespList);
    }


   /* public List<String> numbers(List<String> data){
        List<>
        for (String number : data) {
            String.format("%.2f", Double.parseDouble(number));
        }
    }*/
}
